# -*- coding: UTF-8 -*-
# @Time    : 2021/7/20 23:00
# @Author  : Sun
# @Email   : xxxxxxxxxxx@xxx.com
# @File    : mqtt_connect.py
# @software: PyCharm
# 文件注释  : https://pypi.org/project/paho-mqtt/
import time

import paho.mqtt.client as mqtt
import requests

from common.write_log import WriteLog

"""
MQTT连接封装：
connect -> subscribe -> message
"""
class MQTTConnect:

    log = WriteLog().write_log()
    """
    登录需要有一定的间隔时间
    """
    def __init__(self, jj_uid=None):
        pass

    """
    登录并获取token
    """
    def login(self, jj_uid=None):
        # 定义连接MQTT的UID
        if jj_uid is not None:
            self.login_jjuid = jj_uid
        else:
            self.login_jjuid = '682139016'
        WriteLog().write_log().info(self.login_jjuid)
        self.login_url = "https://test-api.live.jjmatch.com:21102/account/JJLogin"
        self.login_headers = {
            'Host': 'test-api.live.jjmatch.com:21102',
            'User-Agent': 'okhttp/3.12.0',
            'platform': 'PC-Client',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        self.login_data = f'JJUid={self.login_jjuid}&JJToken=zb123456&loginType=4'

        # 添加等待，解决频繁调用Token返回为空的问题
        time.sleep(2.5)
        r = requests.request(method='POST', url=self.login_url, headers=self.login_headers, data=self.login_data)
        result = r.json()
        WriteLog().write_log().info(f'登录API请求结果{result}')
        self.token = result.get('data').get('token')
        WriteLog().write_log().info(f'获取到的Token - {self.token}')
        # 将Token作为MQTT的username参数
        self.ready()
        return self.token

    # The callback for when the client receives a CONNACK response from the server.
    # 定义MQTT连接函数，不可以加self
    def on_connect(self, client, userdata, flags, rc):
        WriteLog().write_log().info("Connected with result code  " + str(rc))
        """
        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        连接后进行订阅操作
        """
        client.subscribe(topic="chat/showRoom-300001")

    # The callback for when a PUBLISH message is received from the server.
    # 定义MQTT Message消息的接收
    def on_message(self, client, userdata, msg):
        self.log.info(msg.topic + " " + str(msg.payload))

    def ready(self):
        # print(userdata)
        # self.log.info(self.login_jjuid)
        # client_id不能重复(客户端登录后无法再创建session)，clean_session设置成False确保session不会被清除
        client = mqtt.Client(client_id=self.login_jjuid, clean_session=False)
        # 此方法定义了用户名&密码的传递
        client.username_pw_set(username=self.token)
        client.on_connect = self.on_connect
        client.on_message = self.on_message
        host = 'test-api.live.jjmatch.com'
        client.connect(host, port=21108, keepalive=60)
        # Blocking call that processes network traffic, dispatches callbacks and
        # handles reconnecting.
        # Other loop*() functions are available that give a threaded interface and a
        # manual interface.
        client.loop_start()


if __name__ == '__main__':
    MQTTConnect().login()
